#!/usr/bin/python
# -*- coding: UTF-8 -*-
# author : bird.zhang@ximalaya.com

import zlib
import pymysql

# 参数定义 begin
host = "192.168.1.161"
port = 3306
user = "naliworld"
passwd = "password!"
db = "microlesson"
table = "tb_favorite_node"
shard_col = u"10086"
# 参数定义 end

# 打开数据库连接
mysql_db = pymysql.connect(host=host, port=port, user=user, passwd=passwd, db=db)
# 使用cursor()方法获取操作游标
cursor = mysql_db.cursor()

# SQL 查询语句
sql = "SELECT node, table_name FROM " + db + "." + table + " order by node"
print("sql:" + sql)
# 执行SQL语句
eff_rows = cursor.execute(sql)
print("node表的行数为：" + str(eff_rows))

# 获取所有记录列表
node_list = cursor.fetchall()
print("记录数为：" + str(len(node_list)))

node_subfix = node_list[0][1]
# Python2.*和c中计算CRC32的方法不一样，要转换一下
# shard_col_crc32 = zlib.crc32(shard_col) & 0xffffffff
shard_col_crc32 = zlib.crc32(bytes(shard_col, encoding="utf-8"))
print("shard_col_crc32=")
print(shard_col_crc32)

for node_record in node_list:
    if node_record[0] >= shard_col_crc32:
        node_subfix = node_record[1]
        break

print(node_subfix)

# 关闭数据库连接
mysql_db.close()
